//
//  MXHomeVC.m
//  MXの衣柜
//
//  Created by 马霄 on 15/8/4.
//  Copyright (c) 2015年 霄 马. All rights reserved.
// 首页

#import "MXHomeVC.h"
//封装的轮播图
#import "MXTopView.h"
//轮播三方
#import "SDCycleScrollView.h"
//封装的AFNetWorking
#import "AFNetworkHandler.h"
//轮播图Model
#import "MXTopModel.h"
//引入图片下载三方
#import "UIImageView+WebCache.h"
//自定义的展示CollectionViewCell
#import "MXHomeContentCollectionViewCell.h"
//精选衣服的详情页面
#import "MXHomeItemsDetailVC.h"
//引入潮品的列表界面
#import "MXHomeFasionVC.h"
//引入洗护的列表界面
#import "MXHomeWashVC.h"

#warning HTML类型的数据怎么解析? 怎么实现点击效果
//轮播详情 HTML网页类型的
#import "MXHomeLunboDetailVC.h"
//加入包邮的轮播图详情
#import "MXHomeMailFreeVC.h"
//加入晒照片的VC
#import "MXHomeShowPhotoVC.h"
// 七夕特别
#import "MXHomeCoupleFestivalVC.h"
// 添加刷新头文件
#import "MJRefresh.h"
// 加载缓冲图标
#import "MBProgressHUD.h"
#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
#import "CycleScrollView.h"


@interface MXHomeVC ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, SDCycleScrollViewDelegate, UIAlertViewDelegate>
@property (nonatomic, retain)  MBProgressHUD *HUD;
@property (nonatomic, retain) UIView *alterView;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) MXTopView *topView;
//===========================轮播图属性部分===========================
//轮播图片地址数组
@property (nonatomic, retain) NSMutableArray *urlStringArray;
//两个小标签的属性接收数组
@property (nonatomic, retain) NSMutableArray *IconImageArray;
// 小标签的标题
@property (nonatomic, retain) NSMutableArray *IconTextArray;
//===========================精选内容属性部分===========================
//精选的所有数据的数组
@property (nonatomic, retain) NSMutableArray *ContentArray;
// 精选商品的Model
@property (nonatomic, retain) MXHomeContentModel *model;
// 轮播图链接数组
@property (nonatomic, retain) NSMutableArray *linkArray;
// 当前页码
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, retain) UIImageView *background;

@property (nonatomic, retain) CycleScrollView *mainScorllView;
@end

@implementation MXHomeVC
- (void)dealloc
{
    [_alterView release];
    [_HUD release];
    [_background release];
    [_linkArray release];
    [_model release];
    [_ContentArray release];
    [_IconImageArray release];
    [_IconTextArray release];
    [_urlStringArray release];
    [_topView release];
    [_collectionView release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Home_titleBackGround"] forBarMetrics:UIBarMetricsDefault];

    
    // 设置一个背景图片
    [self creatBackGroundImage];
    {
    //设置标题
    self.title = @"首页";
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:26 / 255.0 green:62 / 255.0 blue:230 / 255.0 alpha:1];
    self.navigationController.navigationBar.alpha = 0.5;
    }
    
    //添加集合视图
    [self creatCollectionView];
    
    //引用轮播图数据
    [self GetLunBoData];
    //引用精选内容数据
    [self GetContentData];
    
    //全局数组初始化
    self.urlStringArray = [NSMutableArray array];
    self.IconTextArray = [NSMutableArray array];
    self.IconImageArray = [NSMutableArray array];
    self.ContentArray  = [NSMutableArray array];
    self.linkArray = [NSMutableArray array];
    
    
#pragma mark 引用三方设置轮播图
    CGFloat topViewHeight = WIDTH / 375 * 220;
    
//封装的一个TopView 引用于CollectionView的HeaderView
    self.topView = [[[MXTopView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, topViewHeight)] autorelease];
    
    //网络加载 --- 创建带标题的图片轮播器
    self.topView.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    self.topView.cycleScrollView.delegate = self;
    self.topView.cycleScrollView.backgroundColor = [UIColor lightGrayColor];
    self.topView.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolStyleAnimated;
    self.topView.cycleScrollView.placeholderImage = [UIImage imageNamed:@"plaseholder"];
    //标题的数组
    self.topView.cycleScrollView.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
//    [self.view addSubview:self.topView.cycleScrollView];
    
    
    //             --- 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //图片地址的数组
        self.topView.cycleScrollView.imageURLStringsGroup = self.urlStringArray;
    });

    
    
    
    
// 利用Target-Action设计模式 在TopView上的Control添加点击方法
    [self.topView.leftControl addTarget:self action:@selector(leftControlAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.topView.rightControl addTarget:self action:@selector(rightControlAction) forControlEvents:(UIControlEventTouchUpInside)];

    
    
    // 添加刷新方法
    [self refreshTableView];

    
    [self.view insertSubview:self.collectionView aboveSubview:self.background];
    
    // Do any additional setup after loading the view.
}

- (void)creatBackGroundImage
{
    self.background = [[UIImageView alloc] initWithFrame:self.view.bounds];
    self.background.image = [UIImage imageNamed:@"Home_background"];
    [self.view addSubview:self.background];

}
// 添加菊花方法
-(void)uiActivityindicatorviewStart
{
    self.alterView =[[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)] autorelease];
    self.alterView.backgroundColor =[UIColor whiteColor];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.alterView animated:YES];
    [self.HUD show:YES];
    
    [self.view addSubview:self.alterView];
    
}
-(void)uiActivityindicatorviewEnd
{
    [self.alterView removeFromSuperview];
}

#pragma mark - 三方轮播图的点击效果
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    MXHomeLunboDetailVC *lunboVC = [[[MXHomeLunboDetailVC alloc] init] autorelease];
    MXHomeMailFreeVC *mailFreeVC = [[[MXHomeMailFreeVC alloc] init] autorelease];
    MXHomeShowPhotoVC *showPhoto = [[[MXHomeShowPhotoVC alloc] init] autorelease];
//------------------------ 第一张轮播图点击效果 ----------------------

    if (index == self.urlStringArray.count - 2) {
    
        [self presentViewController:mailFreeVC animated:YES completion:^{
        }];
        
    } else if (index == self.urlStringArray.count - 1){
        [self presentViewController:showPhoto animated:YES completion:^{
        }];
    } else {
        
        lunboVC.requestString = self.linkArray[index];
        
        
        [self.navigationController pushViewController:lunboVC animated:YES];

    }
    
}

#pragma mark -- 下拉刷新
-(void)refreshTableView
{
    //    __block MXFindVC *findVC = self;
    [self.collectionView addHeaderWithCallback:^{
        [self GetLunBoData];
        [self GetContentData];
        [self.collectionView headerEndRefreshing];
    }];
    //添加下拉刷新头部控件
    
        [self.collectionView reloadData];
}




#pragma mark - 创建集视图
- (void)creatCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLayout.itemSize = CGSizeMake(WIDTH / 375 * 170, HEIGHT / 667 * 240);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(WIDTH / 375 * 10 , WIDTH / 375 * 10 , 0, WIDTH / 375 * 10);
#pragma mark - 根据TopView手动更改
    flowLayout.headerReferenceSize = CGSizeMake(0, WIDTH / 375 * 210);

    self.collectionView = [[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - HEIGHT / 667 * 64) collectionViewLayout:flowLayout] autorelease];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.collectionView];
    
    
    [self.collectionView registerClass:[MXHomeContentCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self uiActivityindicatorviewStart];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(uiActivityindicatorviewEnd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

    
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}
/************************* 接续轮播图部分数据 **************************/
- (void)GetLunBoData
{
    NSString *lunboString = @"http://api.nanyibang.com/theme?type=2%2C3";
    [AFNetworkHandler GETwithAFNByURL:lunboString completion:^(id result) {
        
        
        // 刷新清空全局数组
        [self.urlStringArray removeAllObjects];
        [self.linkArray removeAllObjects];
        
        NSDictionary *dataDict = result;
        NSArray *dataArr = [dataDict objectForKey:@"data"];
        for (NSDictionary *dic in dataArr) {
            MXTopModel *model = [[MXTopModel alloc] initWithDic:dic];
            //根据返回数据的类型判断 model.type = 2 是轮播图 model.type = 3 是小标题
            if ([model.type isEqualToString:@"2"]) {
                
                [self.urlStringArray addObject:model.theme_image];
                
                [self.linkArray addObject:model.theme_link];
                
            } else if ([model.type isEqualToString:@"3"]) {
                [self.IconTextArray addObject:model.theme_name];
                [self.IconImageArray addObject:model.theme_image];
            }
        }
        //添加标签的信息
        [self.topView.leftImage sd_setImageWithURL:[NSURL URLWithString:[self.IconImageArray objectAtIndex:0]]];
        [self.topView.rightImage sd_setImageWithURL:[NSURL URLWithString:[self.IconImageArray objectAtIndex:1]]];
        self.topView.leftlabel.text = [self.IconTextArray objectAtIndex:0];
        self.topView.rightlabel.text = [self.IconTextArray objectAtIndex:1];
        
    }];

}
/************************* 精选部分数据 **************************/
- (void)GetContentData
{
#warning 网址待拼接
    NSString *contentString = @"http://api.nanyibang.com/campaign?age=19&campaignId=0&campaignType=jingxuan&page=1";
    [AFNetworkHandler GETwithAFNByURL:contentString completion:^(id result) {
        NSDictionary *dataDic = [result objectForKey:@"data"];
        for (NSDictionary *dic in [dataDic objectForKey:@"itemDetail"] ) {
            self.model = [[[MXHomeContentModel alloc] initWithDic:dic] autorelease];
            [self.ContentArray addObject:self.model];
            NSLog(@"%@", self.model);
        }
        [self.collectionView reloadData];
        [self uiActivityindicatorviewEnd];
        
    }];

}


#pragma mark - CollectionView 协议实现部分
/************************* CollectionView Delegate **************************/
//Collection中的组别个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个组别中元件的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.ContentArray.count;
}
//重用机制
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MXHomeContentCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor magentaColor];
    cell.layer.cornerRadius = 8;
    cell.layer.masksToBounds = YES;
    [cell getInfo:self.ContentArray[indexPath.row]];
    return cell;
}
//设置HeaderView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *topView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    [topView addSubview:self.topView];
    return topView;
}
#pragma mark - 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MXHomeItemsDetailVC *ItemVC = [[[MXHomeItemsDetailVC alloc] init] autorelease];
    MXHomeContentModel *model = self.ContentArray[indexPath.row];
    ItemVC.tempNum = model._id;
    [self presentViewController:ItemVC animated:YES completion:^{
        
    }];
}

#pragma mark - 首页标签的点击方法
- (void)leftControlAction
{
//    NSLog(@"潮品专区");
    MXHomeFasionVC *fasionVC = [[[MXHomeFasionVC alloc] init] autorelease];
    [self.navigationController pushViewController:fasionVC animated:YES];
    
}
- (void)rightControlAction
{
//    NSLog(@"洗护专区");
    MXHomeWashVC *washVC = [[[MXHomeWashVC alloc] init] autorelease];
    [self presentViewController:washVC animated:YES completion:^{
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark - 结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
